package a2023.a1008;

import java.util.*;

class StockPrice {

    private HashMap<Integer, Integer> spKey;
    private TreeMap<Integer, Integer> spValue;
    private Integer maxKey = Integer.MIN_VALUE;

    public StockPrice() {
        spKey = new HashMap<Integer, Integer>();
        spValue = new TreeMap<Integer, Integer>();
    }

    public void update(int timestamp, int price) {
        int prevPrice = spKey.getOrDefault(timestamp, 0);
        spKey.put(timestamp, price);
        if (prevPrice > 0) {
            spValue.put(prevPrice, spValue.get(prevPrice) - 1);
            if (spValue.get(prevPrice) == 0) {
                spValue.remove(prevPrice);
            }
        }
        spValue.put(price, spValue.getOrDefault(price, 0) + 1);
        maxKey = Integer.max(timestamp, maxKey);
    }

    public void update2(int timestamp, int price) {
        if (spKey.containsKey(timestamp)) {
            int old = spKey.get(timestamp);
            if (spValue.merge(old, -1, Integer::sum) == 0) {
                spValue.remove(old);
            }
        }
        spKey.put(timestamp, price);
        spValue.merge(price, 1, Integer::sum);
        maxKey = Integer.max(timestamp, maxKey);
    }

    public int current() {
        return spKey.get(maxKey);
    }

    public int maximum() {
        return spValue.lastKey();
    }

    public int minimum() {
        return spValue.firstKey();
    }
}

/**
 * Your StockPrice object will be instantiated and called as such:
 * StockPrice obj = new StockPrice();
 * obj.update(timestamp,price);
 * int param_2 = obj.current();
 * int param_3 = obj.maximum();
 * int param_4 = obj.minimum();
 */